﻿
Imports System.Security.Cryptography




Public Class Form1

    Dim enc As New Seguridad



    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.txtContrasenaCifrada.Text = enc.Cifrar(Me.txtContrasena.Text)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.txtContrasenaDescifrada.Text = enc.Descifrar(Me.txtContrasenaCifrada.Text)
    End Sub

End Class







Public Class Seguridad

    Dim ue As New System.Text.UTF8Encoding
    Dim sec As New RSACryptoServiceProvider
    Dim pcadenaBytesArray(), pcadenaEncriptBytes(), pcadenaDesencriptBytes() As Byte

    Public Function Cifrar(ByVal pcadena As String) As String
        Dim pcadenaEncript As String = ""
        If pcadena <> "" Then
            Try
                pcadenaBytesArray = ue.GetBytes(pcadena)
                pcadenaEncriptBytes = sec.Encrypt(pcadenaBytesArray, True)
                pcadenaEncript = Convert.ToBase64String(pcadenaEncriptBytes)
            Catch ex As Exception
                MessageBox.Show("No se realizó cifrado " & ex.Message)
            End Try
        End If
        Return pcadenaEncript
    End Function

    Public Function Descifrar(ByVal pcadena As String) As String
        Dim pcadenaDesencript As String = ""
        If pcadena <> "" Then
            Try
                'pcadenaBytesArray = ue.GetBytes(pcadena)
                pcadenaDesencriptBytes = sec.Decrypt(Convert.FromBase64String(pcadena), True)
                pcadenaDesencript = ue.GetString(pcadenaDesencriptBytes)
            Catch ex As Exception
                MessageBox.Show("No se realizó cifrado " & ex.Message)
            End Try
        End If
        Return pcadenaDesencript
    End Function




End Class